package com.mq.demo.service;

import com.alibaba.fastjson.JSONObject;
import com.mq.demo.utils.MQConstansUtils;
import lombok.extern.java.Log;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

/**
 * @Author Re
 * @create 2023/2/28 16:59
 * @Description TODO
 */
@Service("mqService")
@Log
public class MQServiceImpl {

    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    /**
     * 发送普通消息
     * @param o
     */
    public void sendMessage(Object o) {
        log.info("发送普通消息消息内容：" + JSONObject.toJSONString(o));
        //省略上面所有代码
        rocketMQTemplate.convertAndSend(MQConstansUtils.TOPIC, o);
    }

    public void sendOneWayMq(Object o){
        log.info("发送一次消息消息内容：" + JSONObject.toJSONString(o));
        rocketMQTemplate.sendOneWay(MQConstansUtils.TOPIC,o);
    }

    public void sendTransactionMsg(Object o,Object arg){
        log.info("发送事物消息消息内容：" + JSONObject.toJSONString(o));
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("txMessage","推送事物消息：" + o);
        //发送事务消息
        rocketMQTemplate.sendMessageInTransaction(MQConstansUtils.TOPIC_TX_MSG, MessageBuilder.withPayload(jsonObject.toJSONString()).build(), arg);
    }
}
